using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NTTHAO.CommonWeb;
using NTTHAO.Web.BL.HighlightLink;
using System.IO;
using NTTHAO.Common;
using NTTHAO.Imaging;
using System.Drawing;

public partial class admin_webparts_Plug_ins_HighlightLink_LinkInput : System.Web.UI.UserControl
{
    public HighlightLinkGroup _Group = null;
    public HighlightLink _Link = null;
    public string _ErrorMsg = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        btnSave.Value = btnSave2.Value = LanguageUtility.GetLanguageText("SAVE", Session);
        chkActive.Text = LanguageUtility.GetLanguageText("ACTIVE", Session);
        
        try
        {
            int groupID = 0;
            Int32.TryParse(Request.QueryString["gid"], out groupID);
            _Group = HighlightLinkGroup.GetItem(groupID);

            if (_Group == null)
            {
                Response.Redirect(this._BackLink, false);
                Response.End();
            }

            string adminCss = _Group.AdminDescriptionCssUrl;
            if (adminCss == "" || adminCss == "#")
            {
                adminCss = string.Empty;
            }
            else
            {
                adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/" + adminCss;
            }
            if (adminCss == string.Empty || !System.IO.File.Exists(Server.MapPath(adminCss)))
            {
                adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default_admin.css";
            }
            if (!System.IO.File.Exists(Server.MapPath(adminCss)))
            {
                adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default.css";
            }
            
            this._ContentCKEditor.ContentsCss = adminCss;
            this._ContentCKEditor.Entities = false;

            if (!IsPostBack)
            {
                txtCurrency.Text = _Group.CurrencyDefault;

                if ("editlink".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
                {
                    int linkID = Int32.Parse(Request.QueryString["id"]);
                    _Link = _Group.GetLink(linkID);

                    if (_Link == null)
                    {
                        Response.Redirect(this._BackLink, false);
                        Response.End();
                    }

                    txtTitle.Text = _Link.Title;
                    txtHref.Text = _Link.Href;
                    cmbTarget.SelectedValue = _Link.Target;
                    chkActive.Checked = _Link.Activated;
                    txtPrice.Text = _Link.Price.ToString("0");
                    chkSaleOff.Checked = _Link.SaleOff;
                    txtSaleOffPrice.Text = _Link.SaleOffPrice.ToString("0");
                    txtCurrency.Text = _Link.Currency;
                    txtUnit.Text = _Link.Unit;
                    this._ContentCKEditor.Text = txtDescription.Text = _Link.Description;
                }
            }
        }
        catch (Exception ex)
        {
            _ErrorMsg = ex.Message + "<br /><br />" + ex.StackTrace;
            return;
        }
    }

    public void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            HighlightLink link = null;
            bool isEditing = "editlink".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase);

            if (isEditing)
            {
                int linkID = Int32.Parse(Request.QueryString["id"]);
                link = _Group.GetLink(linkID);
            }
            else
            {
                link = new HighlightLink();
                link.GroupID = _Group.ID;
            }

            link.Title = txtTitle.Text.Trim();
            link.Href = txtHref.Text.Trim();
            link.Target = cmbTarget.SelectedValue;
            link.Activated = chkActive.Checked;
            if (_Group.PriceAvailable)
            {
                link.Price = Convert.ToInt32(txtPrice.Text.Trim());
                link.SaleOff = chkSaleOff.Checked;
                link.SaleOffPrice = link.SaleOff ? Convert.ToInt32(txtPrice.Text.Trim()) : link.Price;
                link.Currency = txtCurrency.Text.Trim();
                link.Unit = txtUnit.Text.Trim();
            }
            link.Description = (_Group.DescriptionOption == DescriptionOptions.None) ? string.Empty : (_Group.DescriptionOption == DescriptionOptions.Short ? txtDescription.Text.Trim() : _ContentCKEditor.Text.Trim());

            if (isEditing)
            {
                link.Update();
            }
            else
            {
                link.Insert();
            }

            if (_Group.ImageAvailable)
            {
                if (this.SavePostedFiles(fuImage, fuThumb, ref link))
                {
                    link.Update();
                }
            }

            string redirectURL = this._BackLink;
            Response.Redirect(redirectURL, false);
        }
        catch (Exception ex)
        {
            _ErrorMsg = ex.Message + "<br /><br />" + ex.StackTrace;
            return;
        }
    }

    public bool SavePostedFiles(FileUpload fuMain, FileUpload fuThumb, ref HighlightLink link)
    {
        bool changed = false;

        string filePath = Server.MapPath("../" + Constant.UPLOAD_FILE_PATH + _Group.ImagePath);
        if (fuMain.HasFile)
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            if (link.ImageName.Length > 0 && File.Exists(Path.Combine(filePath, link.ImageName)))
            {
                File.Delete(Path.Combine(filePath, link.ImageName));
            }
            link.ImageName = string.Empty;

            string fileName = URLUtilities.GetURLRewriteString(link.Title) + "_" + link.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(fuMain.FileName);
            fuMain.PostedFile.SaveAs(Path.Combine(filePath, fileName));

            if (_Group.AutoResize)
            {
                string resizedImage = ImageUtilities.ResizeImageToJpeg(Path.Combine(filePath, fileName), _Group.ResizeWidth, _Group.ResizeHeight, _Group.ResizeOption, ColorTranslator.FromHtml("#" + _Group.ResizeBackColor), (long)_Group.ResizeQuantity);
                fileName = Path.GetFileName(resizedImage);
            }
            link.ImageName = fileName;
            changed = true;

            if (_Group.ThumbImageOption == ThumbImageOptions.AutoCreate)
            {
                bool thumbChanged = this.SaveThumbImage(fuMain, ref link);
                changed = (changed || thumbChanged);
            }
        }

        if (fuThumb.HasFile && _Group.ThumbImageOption == ThumbImageOptions.Upload)
        {
            bool thumbChanged = this.SaveThumbImage(fuThumb, ref link);
            changed = (changed || thumbChanged);
        }

        return changed;
    }

    public bool SaveThumbImage(FileUpload fuThumb, ref HighlightLink link)
    {
        bool changed = false;
        if (fuThumb.HasFile)
        {
            string filePath = Server.MapPath("../" + Constant.UPLOAD_FILE_PATH + _Group.ImagePath);

            if (link.ThumbImageName.Length > 0 && File.Exists(Path.Combine(filePath, link.ThumbImageName)))
            {
                File.Delete(Path.Combine(filePath, link.ThumbImageName));
            }
            link.ThumbImageName = string.Empty;

            string fileName = URLUtilities.GetURLRewriteString(link.Title) + "_" + link.ID.ToString() + "_thumb_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(fuThumb.FileName);
            fuThumb.PostedFile.SaveAs(Path.Combine(filePath, fileName));

            string resizedImage = ImageUtilities.ResizeImageToJpeg(Path.Combine(filePath, fileName), _Group.ThumbImageWidth, _Group.ThumbImageHeight, _Group.ThumbResizeOption, ColorTranslator.FromHtml("#" + _Group.ThumbResizeBackColor), (long)_Group.ThumbResizeQuantity);
            link.ThumbImageName = Path.GetFileName(resizedImage);
            changed = true;
        }
        return changed;
    }

    public string _BackLink
    {
        get
        {
            return "?type=" + Request.QueryString["type"] + "&name=" + Request.QueryString["name"] + "&action=linklist&id=" + Request.QueryString["gid"];
        }
    }
}
